#include "pyScriptManager.h"
#include "globalsManager.h"
#include "stringFunctions.h"
#include <fstream>
#include <iostream>
#include <sstream>


void addSpaces(std::string* s, int spaces) //this function adds a number of spaces to each new line (used for mass indentation).
{
    for(int z=0; z<spaces; z++)
        s->insert(0," ");
    for(int x=0; x<s->length(); x++)
    {

        if((char)(*s)[x] == '\n')
        {
            for(int z=0; z<spaces; z++)
                s->insert(x+1," ");
        }
    }
}
bool pyScriptManager::loadScript(std::string filePath)
{
    std::ifstream file;
    std::string fileName = getFileName(filePath);

    if(getFileExt(fileName).compare(".py") != 0)
        return false; //not a python file
    file.open(filePath.c_str());
    if(!file)
    {
        std::cout << "Error opening " << filePath << "\n";
        return false;
    }
    std::string line;
    script* s = new script();
    s->scriptData = "";
    s->fileName = fileName;
    std::cout << "Script loaded " << filePath << "\n";
    while (!file.eof())
    {
        getline(file,line);
        s->scriptData += line + "\n";
    }
    scripts.push_back(s);
    return true;
}
std::string pyScriptManager::getScript(std::string fileName)
{
    std::vector<script*>::iterator it;
	for(it = scripts.begin(); it != scripts.end(); it++)
	{
		if( (*it)->fileName == fileName)
            return (*it)->scriptData;
	}
	std::cout << "Error, could not find " << fileName << " was it loaded correctly?\n";
	return "";
}


pyScriptManager* PM()
{
	return pyScriptManager::instance();
}
pyScriptManager::pyScriptManager()
{
//... perform necessary instance initializations
}
pyScriptManager* pyScriptManager::pinstance = 0;// initialize pointer

pyScriptManager* pyScriptManager::instance()
{
	if (!pinstance)
	{
		pinstance = new pyScriptManager; // create sole instance
	}
	return pinstance; // address of sole instance
}

pyScriptManager::~pyScriptManager()
{
	std::vector<script*>::iterator it;
	for(it = scripts.begin(); it != scripts.end(); it++)
	{
		delete (*it);
	}
}

using namespace boost::filesystem; //ALSO CHANGE TO READ LINE INSTEAD OF READ CHARACTER!!!
using namespace std;
void loadScriptDirectory(const path & directory, bool recurse_into_subdirs)
{
    directory_iterator end;

    for( directory_iterator iter(directory) ; iter != end ; ++iter )
    {
        if ( is_directory( *iter ) )
        {
            //std::cout << iter->path() << " (directory)\n" ;
            if( recurse_into_subdirs ) loadScriptDirectory(*iter, true) ;
        }
        std::stringstream s;
        s << iter->path();
        std::string out; s >> out;
        PM()->loadScript(out);
    }

}





